//
//  AppDelegate.m
//  echo
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 Danny. All rights reserved.
//

#import "AppDelegate.h"
#import "FriendCirclesVC.h"
#import "BaseVC.h"
#import "ExploreVC.h"
#import "ActivityVC.h"
#import "RecommendVC.h"
#import "HotVC.h"
#import "MyExploreVC.h"
#import "ClassifyVC.h"
#import "ActivityVC.h"
#import "InformationVC.h"
#import "VideoPlayerVC.h"
#import "MusicPlayerVC.h"
#import <DKNightVersion.h>
#import "SQLHandler.h"
#import "GuideView.h"

#define WIDTH_SCREEN [UIScreen mainScreen].bounds.size.width
#define HEIGHT_SCREEN [UIScreen mainScreen].bounds.size.height

#define WIDTH [UIScreen mainScreen].bounds.size.width / 414
#define HEIGHT [UIScreen mainScreen].bounds.size.height / 736

@interface AppDelegate ()<UITabBarDelegate>
@property (nonatomic, retain)ExploreVC *exploreVC;
@property (nonatomic, retain)RecommendVC *recommendVC;
@property (nonatomic, retain)MyExploreVC *myExploreVC;
@property (nonatomic, retain)ActivityVC *activityVC;
@property (nonatomic, retain)InformationVC *informationVC;
@property (nonatomic, retain)HotVC *hotVC;
@property (nonatomic, retain)ClassifyVC *classifyVC;
@property (nonatomic, retain)UITabBarController *tabBar;
@property (nonatomic, retain)UINavigationController *homeNavi;
@property (nonatomic, retain)UINavigationController *secondNavi;
@property (nonatomic, retain)UINavigationController *thirdNavi;
@property (nonatomic, retain)UINavigationController *fourthNavi;
@end

@implementation AppDelegate

-(void)dealloc{
    [_window release];
    [_exploreVC release];
    [_recommendVC release];
    [_myExploreVC release];
    [_activityVC release];
    [_informationVC release];
    [_hotVC release];
    [_classifyVC release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [NSThread sleepForTimeInterval:0.5];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    // 打开数据库,创建表格
    [SQLHandler openSQL];
    [SQLHandler createSQLTable];
    [SQLHandler createSQLTableForClassifyVC];
    
    FriendCirclesVC *friendCircleVC = [[FriendCirclesVC alloc]init];
    self.homeNavi = [[UINavigationController alloc]initWithRootViewController:friendCircleVC];
    [friendCircleVC release];
    
    
    self.exploreVC = [[ExploreVC alloc]init];
    self.secondNavi = [[UINavigationController alloc]initWithRootViewController:self.exploreVC];
    [_exploreVC release];

    UISegmentedControl *segOfSecond = [[UISegmentedControl alloc]initWithItems:@[@"探索", @"活动"]];
    [self.secondNavi.navigationBar addSubview:segOfSecond];
    [segOfSecond release];
    segOfSecond.frame = CGRectMake( [UIScreen mainScreen].bounds.size.width / 3 - 30 * WIDTH, 3 * HEIGHT, [UIScreen mainScreen].bounds.size.width / 3 + 50 * WIDTH, 35 * HEIGHT);
    segOfSecond.selectedSegmentIndex = 0;
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        [DKNightVersionManager nightFalling];
        segOfSecond.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
        NSDictionary *selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],
                                                 NSForegroundColorAttributeName: [UIColor greenColor]};
        [segOfSecond setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
        NSDictionary *unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                                   NSForegroundColorAttributeName: [UIColor orangeColor]};
        [segOfSecond setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];

    } else {
        
        [DKNightVersionManager dawnComing];
        segOfSecond.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
        NSDictionary *selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],
                                                 NSForegroundColorAttributeName: [UIColor greenColor]};
        [segOfSecond setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
        NSDictionary *unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                                   NSForegroundColorAttributeName: [UIColor orangeColor]};
        [segOfSecond setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    }
    [segOfSecond addTarget:self action:@selector(pushActivityVC:) forControlEvents:UIControlEventValueChanged];
    
    self.recommendVC = [[RecommendVC alloc]init];
    self.thirdNavi = [[UINavigationController alloc]initWithRootViewController:self.recommendVC];
    [_recommendVC release];

    UISegmentedControl *segOfThird = [[UISegmentedControl alloc]initWithItems:@[@"推荐",@"热门"]];
    [self.thirdNavi.navigationBar addSubview:segOfThird];
    [segOfThird release];
    segOfThird.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 3 - 30 * WIDTH, 3 * HEIGHT, [UIScreen mainScreen].bounds.size.width / 3 + 50 * WIDTH, 35 * HEIGHT);
    segOfThird.selectedSegmentIndex = 0;
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        segOfThird.tintColor = [UIColor clearColor];
        NSDictionary *selectedTextAttributes3 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],
                                                  NSForegroundColorAttributeName: [UIColor greenColor]};
        [segOfThird setTitleTextAttributes:selectedTextAttributes3 forState:UIControlStateSelected];
        NSDictionary *unselectedTextAttributes3 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                                    NSForegroundColorAttributeName: [UIColor whiteColor]};
        [segOfThird setTitleTextAttributes:unselectedTextAttributes3 forState:UIControlStateNormal];
    } else {
        
        [DKNightVersionManager dawnComing];

        segOfThird.tintColor = [UIColor clearColor];
        NSDictionary *selectedTextAttributes3 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],
                                                  NSForegroundColorAttributeName: [UIColor greenColor]};
        [segOfThird setTitleTextAttributes:selectedTextAttributes3 forState:UIControlStateSelected];
        NSDictionary *unselectedTextAttributes3 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                                    NSForegroundColorAttributeName: [UIColor orangeColor]};
        [segOfThird setTitleTextAttributes:unselectedTextAttributes3 forState:UIControlStateNormal];

    }
    [segOfThird addTarget:self action:@selector(pushHotVC:) forControlEvents:UIControlEventValueChanged];
    
    self.myExploreVC = [[MyExploreVC alloc]init];
    self.fourthNavi = [[UINavigationController alloc]initWithRootViewController:self.myExploreVC];
    [_myExploreVC release];
    
    UISegmentedControl *segOfFourth = [[UISegmentedControl alloc]initWithItems:@[@"探索",@"分类"]];
    [self.fourthNavi.navigationBar addSubview:segOfFourth];
    [segOfFourth release];
    segOfFourth.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 3 - 30 * WIDTH, 3 * HEIGHT, [UIScreen mainScreen].bounds.size.width / 3 + 50 * WIDTH, 35 * HEIGHT);
    segOfFourth.selectedSegmentIndex = 0;
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        segOfFourth.tintColor = [UIColor clearColor];
        NSDictionary *selectedTextAttributes4 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],
                                                  NSForegroundColorAttributeName: [UIColor greenColor]};
        [segOfFourth setTitleTextAttributes:selectedTextAttributes4 forState:UIControlStateSelected];
        NSDictionary *unselectedTextAttributes4 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                                    NSForegroundColorAttributeName: [UIColor whiteColor]};
        [segOfFourth setTitleTextAttributes:unselectedTextAttributes4 forState:UIControlStateNormal];
    } else {
        
        [DKNightVersionManager dawnComing];
        segOfFourth.tintColor = [UIColor clearColor];
        NSDictionary *selectedTextAttributes4 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],
                                                  NSForegroundColorAttributeName: [UIColor greenColor]};
        [segOfFourth setTitleTextAttributes:selectedTextAttributes4 forState:UIControlStateSelected];
        NSDictionary *unselectedTextAttributes4 = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                                    NSForegroundColorAttributeName: [UIColor orangeColor]};
        [segOfFourth setTitleTextAttributes:unselectedTextAttributes4 forState:UIControlStateNormal];
    }
    
    [segOfFourth addTarget:self action:@selector(pushClassifyVC:) forControlEvents:UIControlEventValueChanged];
    
    self.tabBar = [[UITabBarController alloc]init];
    self.tabBar.viewControllers = @[self.homeNavi, self.secondNavi, self.thirdNavi, self.fourthNavi];
    
    self.homeNavi.tabBarItem = [[UITabBarItem alloc]initWithTitle:nil image:[UIImage imageNamed:@"shouye"] selectedImage:[UIImage imageNamed:@"shouyexuanzhong"]];
    self.homeNavi.tabBarController.tabBar.tintColor = [UIColor greenColor];
    [self.homeNavi.tabBarItem release];
    
    self.secondNavi.tabBarItem = [[UITabBarItem alloc]initWithTitle:nil image:[UIImage imageNamed:@"huodong"] selectedImage:[UIImage imageNamed:@"huodongxuanzhong"]];
    self.secondNavi.tabBarController.tabBar.tintColor = [UIColor greenColor];
    [self.secondNavi.tabBarItem release];
    
    self.thirdNavi.tabBarItem = [[UITabBarItem alloc]initWithTitle:nil image:[UIImage imageNamed:@"yinfu"] selectedImage:[UIImage imageNamed:@"yinfu xuanzhong"]];
    self.thirdNavi.tabBarController.tabBar.tintColor = [UIColor greenColor];
    [self.thirdNavi.tabBarItem release];
    
    self.fourthNavi.tabBarItem = [[UITabBarItem alloc]initWithTitle:nil image:[UIImage imageNamed:@"xiaolian"] selectedImage:[UIImage imageNamed:@"xiaolianxuanzhong"]];
    self.fourthNavi.tabBarController.tabBar.tintColor = [UIColor greenColor];
    [self.fourthNavi.tabBarItem release];

    // tabBar默认页
    self.tabBar.selectedIndex = 2;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"] == NO) {
        self.window.rootViewController = self.tabBar;
    }
    
    [self.homeNavi release];
    [self.secondNavi release];
    [self.thirdNavi release];
    [self.fourthNavi release];
    [_window release];
    [_tabBar release];
    
    // 引导页
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"everLaunched"] == nil) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        
    }
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"] == YES) {
        
        RecommendVC *vc = [[RecommendVC alloc]init];
        self.window.rootViewController = vc;
        
        GuideView *guideView = [[GuideView alloc] initWithFrame:self.window.frame images:@[@"http://img4.duitang.com/uploads/blog/201404/26/20140426105813_uBUnV.thumb.700_0.jpeg", @"http://imgsrc.baidu.com/forum/pic/item/90527acf3bc79f3dedcb9238bda1cd11728b297a.jpg", @"http://cdn.duitang.com/uploads/item/201305/11/20130511000933_kKA3B.jpeg"]];
        [guideView.buttonForInto addTarget:self action:@selector(handleInto) forControlEvents:UIControlEventTouchUpInside];
        
        guideView.tag = 101;
        [self.window addSubview:guideView];
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"everLaunched"];
    }
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"jumpForSecond" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        segOfSecond.selectedSegmentIndex = 0;
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"jumpForThird" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        segOfThird.selectedSegmentIndex = 0;
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"jumpForFourth" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
       
        segOfFourth.selectedSegmentIndex = 0;
    }];
    
    // 网络
    [[NSNotificationCenter defaultCenter] addObserverForName:@"jumpForSecond1" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        segOfSecond.selectedSegmentIndex = 0;
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"jumpForThird1" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        segOfThird.selectedSegmentIndex = 0;
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"jumpForFourth1" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        segOfFourth.selectedSegmentIndex = 0;
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"NoNet1" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSInteger index = self.tabBar.selectedIndex;

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"抱歉,未连接到网络" message:@"请检查您的网络连接" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (index == 0) {
                [self.homeNavi popViewControllerAnimated:YES];

            }else if (index == 1) {
                UIViewController *vc = [self.secondNavi popViewControllerAnimated:YES];
                if ([vc isKindOfClass:[self.activityVC class]]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpForSecond1" object:nil userInfo:nil];
                }
            }else if (index == 2) {
                UIViewController *vc = [self.thirdNavi popViewControllerAnimated:YES];
                if ([vc isKindOfClass:[self.hotVC class]]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpForThird1" object:nil userInfo:nil];
                }
            }else {
                UIViewController *vc = [self.fourthNavi popViewControllerAnimated:YES];
                if ([vc isKindOfClass:[self.classifyVC class]]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpForFourth1" object:nil userInfo:nil];
                }
            }
            
        }];
        
        [alert addAction:sure];
        
        if (alert) {
        
            if (index == 0) {
                [self.homeNavi presentViewController:alert animated:YES completion:^{
                    
                }];
            }else if (index == 1) {
                [self.secondNavi presentViewController:alert animated:YES completion:^{
                    
                }];
            }else if (index == 2) {
                [self.thirdNavi presentViewController:alert animated:YES completion:^{
                    
                }];
            }else {
                [self.fourthNavi presentViewController:alert animated:YES completion:^{
                    
                }];
            }
            
        }
        
    }];

    return YES;
}

// 进入APP
- (void)handleInto{
    GuideView *guideView = [self.window viewWithTag:101];
    [guideView removeFromSuperview];
    self.window.rootViewController = self.tabBar;
}

// SegmentedControl点击方法
- (void)pushActivityVC:(UISegmentedControl *)seg{
    
    switch (seg.selectedSegmentIndex) {
        case 0:

            [self.exploreVC.navigationController popToRootViewControllerAnimated:YES];
            break;
        case 1:
            self.activityVC = [[ActivityVC alloc]init];
            [self.exploreVC.navigationController pushViewController:self.activityVC animated:YES];
            break;
        default:
            break;
    }
}

// SegmentedControl点击方法
- (void)pushHotVC:(UISegmentedControl *)seg{

    switch (seg.selectedSegmentIndex) {
        case 0:
            [self.recommendVC.navigationController popViewControllerAnimated:YES];
            break;
        case 1:
            self.hotVC = [[HotVC alloc]init];
            [self.recommendVC.navigationController pushViewController:self.hotVC animated:YES];
            break;
        default:
            break;
    }
}

// SegmentedControl点击方法
- (void)pushClassifyVC:(UISegmentedControl *)seg{

    switch (seg.selectedSegmentIndex) {
        case 0:
            [self.myExploreVC.navigationController popToRootViewControllerAnimated:YES];
            break;
        case 1:
            self.classifyVC = [[ClassifyVC alloc]init];
            [self.myExploreVC.navigationController pushViewController:self.classifyVC animated:YES];
            break;
        default:
            break;
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
